<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

class Index extends Controller{
	
	//代理首页
    public function index(){
		
		if(!IS_TEST){
		
			$request = Request::instance();
			
			//分享链接
			///?inviterid=AG_20200419170843163501&levels=AgentLevel_005,AgentLevel_006
			
			$inviterid = $request->param('inviterid','');//邀请人ID
			$invitelevels = $request->param('levels','');//邀请新人加入的目标代理等级
			if($inviterid != ''){
				Session::set('register_inviterid',$inviterid);
				Session::set('register_invitelevels',$invitelevels);
			}else{
				Session::delete('register_inviterid');
				Session::delete('register_invitelevels');
			}
			
			//当前登陆状态
			if(!Session::has('agent_id')){
				$this->wxlogin();
				exit();
			}
		}else{
			//测试
			defined('AGENT_ID') or define('AGENT_ID',TEST_AGENT_ID);
			Session::set('agent_id',AGENT_ID);
		}
		//有登陆状态、需要判断是否状态为8
		
		//显示页面
		defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
		$param = ['agentid' => AGENT_ID];
		$response = \ServerHelper::post('agenthome',$param);
		
		$data = $this->J($response);
		if(
			empty($data['flag']) || 
			!isset($data['data']['agent']['status'])
		){
			__log('wechatlogin：agentid['. AGENT_ID . '] in browser, but the user not founded or status not eq 8 in server','weixin_login');
			exit();
		}
		
		if(!IS_TEST){
			if($data['data']['agent']['status'] == 8){
				return view('',['data'=>$data['data']]);
			}else{
				$this->redirect('Member/register');
			}
		}else{
			return view('',['data'=>$data['data']]);
		}
    }
	
	private function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			__log($list,'welogin');
			if(Request::instance()->isAjax()){
				ajax('网络错误');
			}
			exit('net error');
		}
		return $data;
	}
	
	private function wxlogin(){
		
		if(!__iswechat()){
			$this->error('请在微信中登陆');
		}
		
		$cfg = \ServerHelper::GetWeChatConfig();
		if(!isset($cfg['appid'])){
			__log('登录：没有设置微信appid','weixin');
			$this->error('系统错误');
			exit();
		}
		
		$appid = $cfg['appid'];
		
		$request = Request::instance();
		
		$redirect_uri = urlencode($request->domain() . url('Index/wechat_redirect'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize";
		$url.="?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		
		$this->redirect($url);
	}
	
	public function wechat_redirect(){
		//载入配置信息
		$cfg = \ServerHelper::GetWeChatConfig();
		if(
			!isset($cfg['appid']) || 
			!isset($cfg['appsecret'])
			){
			__log('登录：没有设置微信appid或appsecret','weixin');
			$this->error('系统错误');
			exit();
		}
		$appid = $cfg['appid'];
		$appsecret = $cfg['appsecret'];
		
		//拉取请求
		$request = Request::instance();

		//第一步返回的 得到了 Code
		$code = $request->param('code','');
		if($code == ''){
			$this->error('登录发起失败');
		}

		//第二步：通过code换取网页授权access_token
		$url ="https://api.weixin.qq.com/sns/oauth2/access_token";
		$url.="?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = $this->getJson($url);
		if(!isset($info['refresh_token'])){
			$this->error('登陆发起失败');
		}

		//第三步：刷新access_token（如果需要）
		$refresh_token = $info['refresh_token'];
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
		$url.= "?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$info = $this->getJson($url);
		if(
			!isset($info['access_token']) || 
			!isset($info['openid'])
		){
			$this->error('登陆发起失败');
		}

		//第四步：拉取用户信息(需scope为 snsapi_userinfo)
		$access_token = $info['access_token'];
		$openid = $info['openid'];
		$url = "https://api.weixin.qq.com/sns/userinfo";
		$url.= "?access_token=$access_token&openid=$openid&lang=zh_CN";
		$info = $this->getJson($url);

		if(!isset($info['openid'])){
			$this->error('登陆发起失败');
		}

		//后端登陆注册流程
		$param = [
			'wechatid' => $openid,
			'wechatname' => $info['nickname'],
			'headimg' => $info['headimgurl'],
		];
		if(Session::has('register_inviterid')){
			$param['inviterid'] = Session::get('register_inviterid');
		}
		
		//注册或登陆，得到agentid、status
		$response = \ServerHelper::post('wechatlogin',$param);
		$data = $this->J($response);
		
		if(empty($data['flag'])){
			__log('提交微信信息到后端失败','weixin');
			$this->error('系统错误');
		}else{
			$agentInfo = $data['data'];
			Session::set('agent_id',$agentInfo['agentid']);
			if($agentInfo['status'] == 8){
				//所有状态审核完成
				$this->redirect('/');
			}else{
				$this->redirect('Member/register');
			}
		}
	}
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}
	
	//授权证书
	public function certificate(){
		if(!Session::has('agent_id')){
			$this->wxlogin();
			exit();
		}
		defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
		
		//查代理信息
		$pm = [
			'agentid' => AGENT_ID
		];
		$res = \ServerHelper::post('member_mine',$pm);
		$data = $this->J($res);
		if(empty($data['flag'])){
			exit();
		}
		
		//查证书信息
		$pm = [
			'phonenum' => $data['data']['agentinfo']['phonenum']
		];
		$res = \ServerHelper::post('query_agent',$pm);
		$data = $this->J($res);

		if(empty($data['flag'])){
			$this->error($data['msg']);
		}
		
		//生成证书
		$data['data']['template_value']['id_card'][1] = substr_replace($data['data']['template_value']['id_card'][1],'****************',1,16);
		
		if(Cookie::has('certificate' . $pm['phonenum'])){
			
			$data['data']['new_image'] = Cookie::get('certificate' . $pm['phonenum']);
			
		}else{
			//处理图片
			Vendor('CreateCertificate.CreateCertificate');
			$hp = new \CreateCertificate();
			list($flag,$info,$localpath) = $hp->create($data['data']['template_pic'],$data['data']);

			//上传到OSS
			$remotePath = 'uploads/' . date('Ym') . '/' . uniqid() .  '.png';
			$res = \ServerHelper::GetOSSConfig();
			$hp = new \AliyunOSSHelper($res);
			$result = $hp->uploadLocal($localpath,$remotePath,true);
			
			$data['data']['new_image'] = $result['data'];
			
			//缓存一些时间
			Cookie::set('certificate' . $pm['phonenum'],$result['data'],180);
		}
		
		return view('',$data['data']);
	}
	
	public function clearcache(){
		Session::clear();
        echo 'success';
    }
	
	//现金支付且为微信支付方式前 验证支付金额大小，避免大量资金涌入微信商户 
	public function checkwepay(){

		if(!Session::has('agent_id')){
			$this->wxlogin();
			exit();
		}
		defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
		
		/*
		/api/agentwepaycheck.tsl
		参数：
			agentId
			amount
		返回：
			见龚发的截图
		*/
		$pm = [
			'agentid' => AGENT_ID,
			'amount' => Request::instance()->param('amount'),
		];
		$res = \ServerHelper::post('^/agentwepaycheck',$pm);
		$data = $this->J($res);
		
		ajax($data['msg'],$data['flag'] == 1,$data['data']);
	}
	
	//付货款前 验证上级货款够不够[有用，勿删]
	public function checkhuokuanpay(){
		
		if(!Session::has('agent_id')){
			$this->wxlogin();
			exit();
		}
		defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
		
		//checktype=2 升级  1其他
		
		$checktype = Request::instance()->param('checktype',1);
		
		$pm = [
			'agentid' => AGENT_ID,
			'amount' => Request::instance()->param('amount'),
			'checktype' => $checktype == 2 ? 2 : 1,
			'orderid' => Request::instance()->param('orderid')
		];
		$res = \ServerHelper::post('index_checkhuokuanpay',$pm);
		$data = $this->J($res);
		
		ajax($data['msg'],$data['flag'] == 1,$data['data']);
		
	}
	
	
}
